package com.xr.blog.controller;

import com.xr.blog.exception.BlogException;
import com.xr.blog.pojo.BlogArticle;
import com.xr.blog.pojo.BlogSpider;
import com.xr.blog.service.BlogSpiderService;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.constant.Code;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;


/**
 * 爬虫规则
 *
 * @author XRJ
 * @email 1033835209@qq.com
 * @date 2020-07-07 20:31:38
 */
@RestController
@RequestMapping("/squirrelblog")
public class BlogSpiderController {
    @Autowired
    private BlogSpiderService blogSpiderService;


    @GetMapping(value = "/spider/list",produces = "application/json;charset=UTF-8")
    public Result<List<BlogSpider>> list(){
        return Result.of(Code.SC_OK.getState(),"查询成功",blogSpiderService.list());
    }


    @GetMapping(value = "/spider/getById",produces = "application/json;charset=UTF-8")
    public Result<BlogSpider> info(Long id){
        return Result.of(Code.SC_OK.getState(),"查询成功",blogSpiderService.getById(id));
    }


    @PostMapping(value = "/spider/addOrUpdate",produces = "application/json;charset=UTF-8")
    public Result<BlogSpider> save(@RequestBody @Validated({Update.class, Insert.class}) BlogSpider spider){
        //ValidatorUtils.validate(spider);
        blogSpiderService.saveOrUpdate(spider);
        return Result.of(Code.SC_OK.getState(),"保存成功",spider);
    }


    @PostMapping(value = "/spider/spiderArticle",produces = "application/json;charset=UTF-8")
    public Result spiderArticle(@RequestParam(value = "id",required = false)Long id,
                                @RequestParam(value = "url",required = false)String url){
        BlogSpider spider=blogSpiderService.getById(id);
        if(StringUtils.isBlank(url)){
            return Result.of(Code.SC_PRECONDITION_FAILED.getState(),"文章链接不能为空",null);
        }
        if(spider==null){
            return Result.of(Code.SC_PRECONDITION_FAILED.getState(),"规则不能为空",null);
        }
        BlogArticle article;
        try {
            //此处服务层接口还未开发
            article=blogSpiderService.spiderArticle(spider,url);
        } catch (IOException e) {
            throw new BlogException(40005,"文章抓取失败：",e);
        }
        return article!=null?Result.of(Code.SC_OK.getState(),"抓取成功",article):Result.of(40005,"抓取失败",null);
    }



    @DeleteMapping(value = "/spider/delete",produces = "application/json;charset=UTF-8")
    public Result delete(Long id){
        return blogSpiderService.removeById(id)?Result.of(Code.SC_OK.getState(),"删除成功",null):Result.of(Code.DEL_FAIL.getState(),"删除失败",null);
    }
}
